package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.file.service.FileStorageService;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmMateriaDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.utils.thread.WmThreadLocalUtil;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.service.WmMaterialService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.*;

/**
 * @author 10161
 */
@Service
@Transactional
@Slf4j
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {
    @Autowired
    private FileStorageService fileStorageService;

    /**
     * 图片上传业务实现
     *
     * @param multipartFile
     * @return wmMaterial 给前端作为图片回显
     */
    @Override
    public ResponseResult uploadPicture(MultipartFile multipartFile) {
        //1.从multipartFile 中解析出要上传的图片内容 要有预见性的判断是否为空
        if (multipartFile == null || multipartFile.getSize() == 0) {
            //传了空文件
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "图片无效！");
        }
        //2.导入我们之前写的图片上传的起步依赖，在nacos中配置好minio的配置
        //设置好要上传的文件的一些参数（prefix,filename,inInputStream）

        //replace 为替换方法，在这里表示把字符串中的“-”替换成“”
        String fileName = UUID.randomUUID().toString().replace("-", "");
        String originalFilename = multipartFile.getOriginalFilename();
        //这里便会将原文件名截取到其后缀
        int i = originalFilename.lastIndexOf(".");
        String postfix = originalFilename.substring(originalFilename.lastIndexOf("."));
        String finalFileName = fileName + postfix;

        //3.调用文件上传的api上传图片
        String filedId = "";
        try {
            String path = fileStorageService.uploadImageFile("", fileName + postfix, multipartFile.getInputStream());
            log.info("文件上传成功到minio，文件名为：{}", path);
            filedId = path;
        } catch (IOException e) {
            e.printStackTrace();
            log.error("文件上传失败！");
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "图片无效！");
        }

        //4.将其返回值（文件上传成功的路径）保存对应的数据库数据
        WmMaterial wmMaterial = new WmMaterial();
        /* wmMaterial.setUserId(WmThreadLocalUtil.getUser().getApUserId());*/
        wmMaterial.setUrl(filedId);
        wmMaterial.setType((short) 0);
        wmMaterial.setIsCollection((short) 0);
        wmMaterial.setCreatedTime(new Date());
        wmMaterial.setUserId(1102);
        //todo：元数据填充出现错误，修正一下
        boolean save = save(wmMaterial);
        if (!save) {
            //数据库持久化失败
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR, "未知错误");
        }

        //5.返回结果
        return ResponseResult.okResult(wmMaterial);
    }

    /**
     * 查询数据list的业务实现
     *
     * @param wmMateriaDto
     * @return 返回数据库查询到的数据
     */
    @Override
    public ResponseResult getList(WmMateriaDto wmMateriaDto) {
        //前端传来的数据 有 isCollection  page  size ,说明我们是需要用mybatis实现分页的(使用分页拦截器)
        //1.将封装的数据进行获取，进行预见性的空值判断
        Short isCollection = wmMateriaDto.getIsCollection();
        Integer size = wmMateriaDto.getSize();
        Integer page = wmMateriaDto.getPage();
        if (size == 0 || page == 0 || isCollection == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE, "未知错误，缺少参数！");
        }
        //2.根据这三个查询条件去查询数据库，并返回结果
        LambdaQueryWrapper<WmMaterial> wrapper = new LambdaQueryWrapper<>();
        IPage<WmMaterial> iPage = new Page<>(page, size);
        //2.1 mybatis中分页查询调用 page()方法，传iPage 和查询条件 Wrapper
        IPage<WmMaterial> page1 = page(iPage, wrapper);
        List<WmMaterial> wmMaterialList = page1.getRecords();
        //3.对结果进行是否为空判断
        if (wmMaterialList.isEmpty()) {
            //查不到数据，返回错误
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //4.将查询到的数据封装好返回给前端进行展示
        ResponseResult responseResult = new PageResponseResult(wmMateriaDto.getPage(), wmMateriaDto.getSize(), (int) page1.getTotal());
        responseResult.setData(wmMaterialList);
        return responseResult;

    }

    /**
     * 根据图片id删除图片
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult deletePicture(Integer id) {
        //1.对传来的id进行预见性判断
        if (id == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.根据id去查数据库进行删除操作
        LambdaQueryWrapper<WmMaterial> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(WmMaterial::getId, id);

        try {
            remove(wrapper);
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "文件删除失败！");
        }
    }

    /**
     * 根据图片id进行收藏
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult collect(Integer id) {
        if (id == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        LambdaQueryWrapper<WmMaterial> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(WmMaterial::getId, id);
        WmMaterial updateObject= getById(id);
        updateObject.setIsCollection((short)1);
        try {
            update(updateObject, wrapper);
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "文件收藏失败！");
        }
    }

    /**
     * 根据图片id进行图片收藏
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult cancelCollect(Integer id) {
        if (id == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        LambdaQueryWrapper<WmMaterial> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(WmMaterial::getId, id);
        WmMaterial updateObject= getById(id);
        updateObject.setIsCollection((short)0);
        try {
            update(updateObject, wrapper);
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "取消文件收藏失败！");
        }

    }


}
